package com.iss.wyy.util;




import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassUtil {
    /**
     * 获取类加载器
     * @return
     */
   public static ClassLoader getClassLoader(){
       return Thread.currentThread().getContextClassLoader();
   }

    /**
     * 加载类
     * @param className
     * @param isInitialized 是否初始化
     * @return
     */
    public static Class<?> loadClass(String className,boolean isInitialized){
        Class<?> cls;
        try {
            cls = Class.forName(className,isInitialized,getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return cls;
    }
    /**
     * 获取指定包名下的所有类
     */
    public static Set<Class<?>> getClassSet(String packageName){
        return getClassSet(packageName,true);
    }

    /**
     *
     * @param packageName 包名
     * @param bl 是否递归子包里的类
     * @return
     */
    public static Set<Class<?>> getClassSet(String packageName,boolean bl){
        Set<Class<?>> classSet = new HashSet<>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".","/"));
            //遍历迭代器
            while (urls.hasMoreElements()){
                URL url = urls.nextElement();
                if(url !=null){
                    String protocol = url.getProtocol();
                    //得到资源的URL可能是file:这种格式也可能是jar:格式，如果是file则将URL转成磁盘的文件系统路径，
                    // 然后用File来读取资源。如果是jar则使用JarURLConnection 来获取JarFile来操作
                    if (protocol.equals("file")){
                        //String packagePath = url.getPath().replaceAll("%20"," ");
                        //进行url编码
                        String packagePath = URLDecoder.decode(url.getPath(),"utf-8");
                        addFile(classSet,packagePath,packageName,bl);
                    }else if(protocol.equals("jar")){
                        addClassJar(classSet, url);
                    }
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return classSet;
    }

    /**
     * 获取指定jar包下的所有类
     */
    private static void addClassJar(Set<Class<?>> classSet, URL url) throws IOException {
        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
        if (jarURLConnection!=null){
            JarFile jarFile = jarURLConnection.getJarFile();
            if (jarFile!=null){
                //遍历jar里面的所有class
                Enumeration<JarEntry> jarEntries = jarFile.entries();
                while (jarEntries.hasMoreElements()){
                    JarEntry jarEntry = jarEntries.nextElement();
                    String jarEntryName = jarEntry.getName();
                    if (jarEntryName.endsWith(".class")){
                        //去掉后缀 只要包名+类名
                        String className =jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                        addClass(classSet,className);
                    }
                }
            }
        }
    }
    /**
     * 递归获取指定文件名下的所有类
     */
    private static void addFile(Set<Class<?>> classSet, String packagePath, String packageName,boolean bl){
        //获取该路径下所有文件和文件夹
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            //过滤掉非java的类文件
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")) ||file.isDirectory();
            }
        });

        for (File file :files) {
            String fileName =file.getName();
            //如果是文件，拼接包名+类名并加入Set
            if(file.isFile()){
                String className = fileName.substring(0,fileName.lastIndexOf("."));
                if(StringUtils.isNotEmpty(packageName)){
                    className = packageName + "." + className;
                }
                addClass(classSet,className);

                //是包文件夹，继续递归调用自己 包名和路径名 都要多拼接一层名字再递归
            }else {
                //拼接包名
                String subPackagePath = fileName;
                if (StringUtils.isNotEmpty(packagePath)){
                    subPackagePath = packagePath + "/"+ subPackagePath;
                }
                //拼接路径名
                String subPackageName = fileName;
                if(StringUtils.isNotEmpty(packageName)){
                    subPackageName = packageName + "." + subPackageName;
                }
                //递归
                if (bl){
                    addFile(classSet,subPackagePath,subPackageName,bl);
                }
            }
        }
    }

    /**
     * 向set中添加获取到的class
     */
    private static void addClass(Set<Class<?>> classSet, String className){
        Class<?> cls = loadClass(className,false);
        //System.out.println(className);
        classSet.add(cls);
    }


}
